package com.foreverwin.mes.lims.job;

import com.foreverwin.mes.lims.model.ItemTank;
import com.foreverwin.mes.lims.service.ItemTankService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 定时更新呆滞时间，监控是否超过上限，超过发送警报
 * @author Max
 * @since 2020-03-13
 */
@Component
@Configurable
@EnableScheduling
public class MonitorInactiveTime {

    private static Logger logger = LoggerFactory.getLogger(MonitorInactiveTime.class);

    @Autowired
    private ItemTankService itemTankService;


    @Scheduled(cron = "0 */1 * * * ?")
    public void monitorTank(){
        logger.info( "<<<<<<=======定时监控呆滞时间是否超过上限:"  );
        try {
            List<ItemTank> itemTankList = itemTankService.selectCurrentAllTank();
            if (itemTankList != null && itemTankList.size() > 0) {
                for (ItemTank itl : itemTankList) {
                    if (itl.getStartTime() != null) {
                        Date currentTime = new Date();
                        //int inactiveTime = new Long((currentTime.getTime() - itl.getStartTime().getTime()) / (1000 * 60 * 60)).intValue();
                        Double inactiveTime = new Double(currentTime.getTime() - itl.getStartTime().getTime()) / (1000 * 60 * 60);
                        BigDecimal bigScale = new BigDecimal(inactiveTime).setScale(1,BigDecimal.ROUND_UP);
                        itl.setInactiveTime( bigScale );
                        if (currentTime.getTime() < itl.getEstimateLowerTime().getTime() && bigScale.compareTo( new BigDecimal(itl.getUpperLimit()) ) <= 0 ) {
                            //罐子内物料不可用
                            itl.setStatus("0");
                        } else if (currentTime.getTime() >= itl.getEstimateLowerTime().getTime() && currentTime.getTime() <= itl.getEstimateUpperTime().getTime()) {
                            //罐子内物料正常
                            itl.setStatus("1");
                        } else if (currentTime.getTime() > itl.getEstimateUpperTime().getTime()) {
                            //罐子内物料呆滞超时
                            itl.setStatus("2");
                            //发送超时警报
                        }
                        itemTankService.updateById(itl);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
